import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
  // 修改基础路径，确保在端口8765上也能正确加载
  base: process.env.NODE_ENV === 'production' ? '/' : '/',
  plugins: [
    vue(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
    },
  },
  // 配置静态资源目录
  publicDir: 'public',
  // 配置静态资源处理
  assetsInclude: ['**/*.png', '**/*.jpg', '**/*.jpeg', '**/*.gif', '**/*.svg'],
  server: {
    host: true,
    proxy: {
      "/api": {
        target: "http://localhost:8089",
        // target: "http://192.168.1.119:8089",
        changeOrigin: true, //支持跨域
        rewrite: (path) => path.replace(/^\/api/, ''), 
      },
      "/profile": {
        target: "http://localhost:8089",
        // target: "http://192.168.1.119:8089",
        changeOrigin: true,
      },
      "/images": {
        target: "http://localhost:8089",
        // target: "http://192.168.1.119:8089",
        changeOrigin: true,
      }
    },
  },
  // 优化构建配置
  build: {
    // 启用CSS代码分割
    cssCodeSplit: true,
    // 启用源码映射
    sourcemap: false,
    // 配置Rollup选项
    rollupOptions: {
      output: {
        // 静态资源分类打包
        chunkFileNames: 'static/js/[name].js',
        entryFileNames: 'static/js/[name].js',
        assetFileNames: (assetInfo) => {
          // 根据文件类型分类存放资源
          const fileType = assetInfo.name.split('.').pop().toLowerCase();
          const typeDirectory = {
            png: 'images',
            jpg: 'images',
            jpeg: 'images',
            gif: 'images',
            svg: 'images',
            webp: 'images',
            ico: 'images',
            css: 'css',
            // 其他资源类型到可以添加到这里
          }[fileType] || 'assets';
          
          return `static/${typeDirectory}/[name].[ext]`;
        },
        // 拆分代码，优化加载性能
        manualChunks: {
          vue: ['vue', 'vue-router', 'pinia'],
          elementPlus: ['element-plus'],
        },
      },
    },
    // 配置CSS压缩
    cssMinify: 'lightningcss',
    // 启用gzip压缩
    minify: 'terser',
    terserOptions: {
      compress: {
        // 生产环境移除console
        drop_console: true,
        drop_debugger: true,
      },
    },
  },
})
